import { Processor, IProcessor } from '@midwayjs/bullmq';
import { JyLoginProService } from '../service/jyLoginPro.service';
import { Inject } from '@midwayjs/core';
import { PuppeteerTaskService } from '../service/task.service';

@Processor(
  'jyLoginPro',
  {
    attempts: 1, // 重试次数
  },
  {
    concurrency: 2, // 并发数
  }
)
export class JyLoginProProcessor implements IProcessor {
  @Inject()
  jyLoginProService: JyLoginProService;
  @Inject()
  puppeteerTaskService: PuppeteerTaskService; // 注入服务

  // async execute(data: any) {
  //   //获取账号密码次数
  //   let count = 0;
  //   //获取账号密码
  //   let accountPassword = (await this.jyLoginProService.getCard(data.k)) as any;
  //   let  ctx = null;
  //   try {
  //     // 如果resdata.data.phone为空或者为null 则继续10次每次1.5秒，如果还未获取到则报错
  //     while (!accountPassword?.data?.data?.phoneNum) {
  //       if (count > 10) {
  //         throw new Error('获取账号密码失败');
  //       }
  //       console.log('获取账号密码失败，正在重试...');
  //       await new Promise(resolve => setTimeout(resolve, 1500));
  //       accountPassword = await this.jyLoginProService.getCard(data.k);
  //       count++;
  //     }
  //     ctx = await this.puppeteerTaskService.createPage()
  //     await this.jyLoginProService.login(
  //       data.k,
  //       ctx,
  //       accountPassword.data.data
  //     );
  //   } catch (error) {
  //     //TODO
  //     await this.jyLoginProService.failNotify(
  //       data.k,
  //       accountPassword?.data?.data?.phoneNum || ''
  //     );
  //     await ctx.close();
  //     throw error;
  //   }
  // }

  async execute(data: any) {
    let count = 0;
    let accountPassword = (await this.jyLoginProService.getCard(data.k)) as any;
    let ctx = null;

    try {
      while (!accountPassword?.data?.data?.phoneNum) {
        if (count > 10) {
          throw new Error('获取账号密码失败');
        }
        console.log('获取账号密码失败，正在重试...');
        await new Promise(resolve => setTimeout(resolve, 1500));
        accountPassword = await this.jyLoginProService.getCard(data.k);
        count++;
      }
      ctx = await this.puppeteerTaskService.createPage();
      await this.jyLoginProService.login(
        data.k,
        ctx,
        accountPassword.data.data
      );
    } catch (error) {
      // 新增重试逻辑
      if (error.message.includes('获取账号密码失败')) {
        throw new Error(`获取账号密码失败`);
      }
      const MAX_RETRIES = 3; // 最大重试次数
      let retryCount = 0;
      let lastError = error;

      while (retryCount < MAX_RETRIES) {
        try {
          // 每次重试创建新上下文（避免状态污染）
          if (ctx) await ctx.close();
          ctx = await this.puppeteerTaskService.createPage();

          // 指数退避等待（参考网页5的实现）
          await new Promise(resolve =>
            setTimeout(resolve, 1000 * Math.pow(2, retryCount))
          );

          await this.jyLoginProService.login(
            data.k,
            ctx,
            accountPassword.data.data
          );
          return; // 重试成功直接返回
        } catch (retryError) {
          lastError = retryError;
          retryCount++;
          console.warn(`登录失败，第 ${retryCount} 次重试`, retryError);
        }
      }
      // 重试全部失败后执行
      await this.jyLoginProService.failNotify(
        data.k,
        accountPassword?.data?.data?.phoneNum || ''
      );
      await ctx?.close();
      throw new Error(
        `登录失败（共尝试 ${MAX_RETRIES + 1} 次）: ${lastError.message}`
      );
    }
  }
}
